package com.zp.self.testpackage;

import com.alibaba.fastjson.JSONObject;
import com.zp.self.entity.OrderStep;
import com.zp.self.entity.ProduceMessage;
import com.zp.self.producer.ProduceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 本类只用于测试服务，实际不存在
 */
@RestController()
@Slf4j
@RequestMapping("/send")
public class TestRocketMQSendController {
    @Resource
    private ProduceService produceService;

    @GetMapping("/sendSyncMsg")
    public String sendSyncMsg(String topic,String content) throws Exception {
        produceService.sendSyncMsg(new ProduceMessage(topic,null,content));
        return "成功发送一条同步消息";
    }
    @GetMapping("/sendAsyncMsg")
    public String sendAsyncMsg(String topic,String content) throws Exception {
        produceService.sendAsyncMsg(new ProduceMessage(topic,null,content));
        return "成功发送一条异步消息";
    }

    @GetMapping("/sendTransactionMsg")
    public String sendTransactionMsg(String topic,String content) throws Exception {
        produceService.sendTransactionMsg(new ProduceMessage(topic,null,content));
        return "成功发送一条事务消息";
    }

    @GetMapping("/sendMsgOrder")
    public String sendMsgOrder(String topic) throws Exception {

        List<OrderStep> orderSteps = OrderStep.buildOrdes();
        for (OrderStep orderStep : orderSteps) {
            String body = JSONObject.toJSONString(orderStep);
            produceService.sendMsgOrder(new ProduceMessage(topic, null, body), (int) orderStep.getOrderId());
        }
        return "成功发送顺序消息";
    }

    //？？？
    @GetMapping("/sendOneWayMsg")
    public String sendOneWayMsg(String topic,String content) throws Exception {
        produceService.sendOneWayMsg(new ProduceMessage("my-topic","aa","oneway"));
        return "成功发送一条单向消息";
    }



    //------------------------ 压力测试 ---------------------
    @GetMapping("/stress-testing")
    public boolean createMessage(String topic) {

        log.info("创建一个用户消息开始...........");
        List<User> list = new ArrayList<>();

        for(int i = 0;i< 1000000;i++){
            list.add(new User("张三"+"-"+i, i));
        }

        list.parallelStream().forEach(u->{
            try {
                produceService.sendSyncMsg(new ProduceMessage(topic,null, JSONObject.toJSONString(u)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return true;
    }
}

